package fr.emse.tatiana.display;


import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;

import fr.emse.tatiana.display.DisplayFileReader;
import fr.emse.tatiana.display.DisplayFileWriter;

/**
 * A file which stores key:value pairs as a Tatiana Info File. Changes are not written to disk 
 * until save is called
 * 
 * @author dyke
 *
 */
public class PropertyFile {
	private Map<String,String> vars;
	private IFile file;

	public PropertyFile(IFile file) {
		this.file = file;
		this.vars = new HashMap<String,String>();
		try {
			file.refreshLocal(IResource.DEPTH_ZERO, null);
		} catch (CoreException e) {
			//do nothing
		}
		if (file.exists()) {
			DisplayFileReader reader = new DisplayFileReader(file.getLocation().toString());
			if( !reader.selectFirstItem() ) {
				return;
			} else {
				boolean hasinfo = reader.selectFirstInfo();
				while(hasinfo) {
					reader.updateInfoValue("String");
					this.setProperty(reader.infoName(),(String)reader.infoValue());
					hasinfo = reader.selectNextInfo();
				}
			}
		}
	}

	public void setProperty(String key, String value) {
		vars.put(key, value);
	}

	public String getProperty(String key) {
		return vars.get(key);
	}

	public IFile getfile() {
		return file;
	}

	/**
	 * Writes the changes to disk
	 */
	public void save() {
		DisplayFileWriter writer = new DisplayFileWriter(file.getLocation().toString());
		writer.newItem();
		for (String key : vars.keySet()) {
			writer.newInfo(key, "", vars.get(key));
		}
		writer.close();
	}
}
